package com.ip.user.api;

import com.ip.user.models.common.annotation.RequiresPermission;
import com.ip.user.models.service.PermissionService;
import com.ip.user.models.service.SysUserService;
import com.ip.user.models.vo.SysPermissionVO;
import com.ip.user.models.vo.SysUserGroupVO;
import com.ip.user.models.vo.UserVO;
import com.ip.user.mapper.SysUserGroupMapper;
import com.ip.common.constant.Result;
import com.ip.common.enums.CodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户组和权限管理控制器
 * author 刘丰源
 */
@RestController
@RequestMapping( "/api/permission")
public class UserGroupPermissionController {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private SysUserService sysUserService;
    
    @Autowired
    private SysUserGroupMapper userGroupMapper;

    /**
     * 设置用户的用户组（先移除用户当前所有用户组，再添加到指定用户组）
     *
     * @param userId   用户ID
     * @param groupIds 用户组ID列表（可选，如果不提供则表示移除所有用户组）
     * @return 操作结果
     */
    @PostMapping("/set-user-groups")
    @RequiresPermission("group_assign")
    public Result<Boolean> setUserGroups(@RequestParam Integer userId, @RequestBody(required = false) List<Integer> groupIds) {
        try {
            // 检查用户是否存在
            UserVO user = sysUserService.getUserById(userId);
            if (user == null) {
                Result<Boolean> result = new Result<>();
                result.setCode(CodeEnum.FAIL_100001.getCode());
                result.setMsg("用户不存在");
                result.setData(false);
                return result;
            }

            // 设置用户组
            boolean success = permissionService.setUserGroups(userId, groupIds);

            Result<Boolean> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            if (success) {
                if (groupIds != null && !groupIds.isEmpty()) {
                    result.setMsg("用户组设置成功");
                } else {
                    result.setMsg("用户已从所有用户组中移除");
                }
            } else {
                result.setMsg("用户组设置失败");
            }
            result.setData(success);
            return result;
        } catch (Exception e) {
            Result<Boolean> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg("操作失败: " + e.getMessage());
            result.setData(false); // 修改这行，确保返回了数据
            return result;
        }
    }

    /**
     * 为用户组分配权限
     *
     * @param groupId 用户组ID
     * @param permIds 权限ID列表
     * @return 操作结果
     */
    @PostMapping("/assign-permissions-to-group")
    @RequiresPermission("permission_assign")
    public Result<Boolean> assignPermissionsToGroup(@RequestParam Integer groupId, @RequestBody(required = false) List<Integer> permIds) {
        try {
            // 为用户组设置权限（先删除所有权限，再重新分配）
            boolean success = permissionService.setGroupPermissions(groupId, permIds);

            Result<Boolean> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            if (success) {
                if (permIds != null && !permIds.isEmpty()) {
                    result.setMsg("权限成功分配到用户组");
                } else {
                    result.setMsg("用户组的所有权限已移除");
                }
            } else {
                result.setMsg("权限分配到用户组失败");
            }
            result.setData(success);
            return result;
        } catch (Exception e) {
            Result<Boolean> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg("操作失败: " + e.getMessage());
            result.setData(false); // 修改这行，确保返回了数据
            return result;
        }
    }

    /**
     * 获取用户所属的所有用户组
     *
     * @param userId 用户ID
     * @return 用户组列表
     */
    @GetMapping("/user-groups/{userId}")
    @RequiresPermission("group_view")
    public Result<List<SysUserGroupVO>> getUserGroups(@PathVariable Integer userId) {
        try {
            List<SysUserGroupVO> userGroups = permissionService.getUserGroups(userId);
            Result<List<SysUserGroupVO>> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(userGroups);
            return result;
        } catch (Exception e) {
            Result<List<SysUserGroupVO>> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg("查询失败: " + e.getMessage());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        }
    }

    /**
     * 获取用户组的所有权限
     *
     * @param groupId 用户组ID
     * @return 权限列表
     */
    @GetMapping( "/group/{groupId}/permissions")
    @RequiresPermission("permission_view")
    public Result<List<SysPermissionVO>> getGroupPermissions(@PathVariable Integer groupId) {
        try {
            List<SysPermissionVO> permissions = permissionService.getGroupPermissions(groupId);
            Result<List<SysPermissionVO>> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(permissions);
            return result;
        } catch (Exception e) {
            Result<List<SysPermissionVO>> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg("查询失败: " + e.getMessage());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        }
    }
    
    /**
     * 获取所有权限列表
     *
     * @return 权限列表
     */
    @GetMapping("/permissions/all")
    @RequiresPermission("permission:list:view")
    public Result<List<SysPermissionVO>> getAllPermissions() {
        try {
            List<SysPermissionVO> permissions = permissionService.getAllPermissions();
            Result<List<SysPermissionVO>> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(permissions);
            return result;
        } catch (Exception e) {
            Result<List<SysPermissionVO>> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg("查询失败: " + e.getMessage());
            result.setData(null);
            return result;
        }
    }
    
    /**
     * 创建用户组
     */
    @PostMapping("/groups")
    @RequiresPermission("sys:group:add")
    public Result<SysUserGroupVO> createUserGroup(@RequestBody SysUserGroupVO userGroupVO) {
        try {
            // 设置创建和更新时间
            userGroupVO.setCreateTime(LocalDateTime.now());
            userGroupVO.setUpdateTime(LocalDateTime.now());
            
            userGroupMapper.insertUserGroup(userGroupVO);
            
            Result<SysUserGroupVO> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(userGroupVO);
            return result;
        } catch (Exception e) {
            Result<SysUserGroupVO> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg(e.getMessage());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        }
    }


    /**
     * 获取所有用户组
     */
    @GetMapping("/all-groups")
    @RequiresPermission("group_view")
    public Result<List<SysUserGroupVO>> getAllUserGroups() {
        try {
            List<SysUserGroupVO> userGroups = userGroupMapper.selectAllUserGroups();
            
            Result<List<SysUserGroupVO>> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(userGroups);
            return result;
        } catch (Exception e) {
            Result<List<SysUserGroupVO>> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg(e.getMessage());
            result.setData(null);
            return result;
        }
    }
    
    /**
     * 更新用户组
     */
    @PutMapping("update/groups/{id}")
    @RequiresPermission("sys:group:update")
    public Result<SysUserGroupVO> updateUserGroup(@PathVariable Integer id, @RequestBody SysUserGroupVO userGroupVO) {
        try {
            // 设置用户组ID和更新时间
            userGroupVO.setGroupId(id);
            userGroupVO.setUpdateTime(LocalDateTime.now());
            
            userGroupMapper.updateUserGroup(userGroupVO);
            
            Result<SysUserGroupVO> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(userGroupVO);
            return result;
        } catch (Exception e) {
            Result<SysUserGroupVO> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg(e.getMessage());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        }
    }
    
    /**
     * 删除用户组
     */
    @DeleteMapping("delete/groups/{id}")
    @RequiresPermission("sys:group:delete")
    public Result<Void> deleteUserGroup(@PathVariable Integer id) {
        try {
            userGroupMapper.deleteUserGroup(id);
            
            Result<Void> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        } catch (Exception e) {
            Result<Void> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg(e.getMessage());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        }
    }
}